package nl.tue.be.ds.duraark.bSDD.dump;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import javax.ws.rs.core.MediaType;

import nl.tue.be.ds.duraark.bSDD.ClientUtilities;
import nl.tue.be.ds.duraark.bSDD.DataBaseUtilities;

import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.map.ObjectMapper;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.UniformInterfaceException;
import com.sun.jersey.api.client.WebResource;


public class ConInRelSearchPerGuidCallable implements Callable<Integer> {
	
	private String searchGuid;
	private final String searchByGuidUrl = "http://bsddpilot.catenda.no/api/4.0/IfdConcept/";
	
	
	public ConInRelSearchPerGuidCallable(String searchGuid) {
		this.searchGuid = searchGuid;
	}

	public Integer call() throws Exception {
		
		Integer it = new Integer(dumpPerGuid(searchPerGuid()));
		DataBaseUtilities.db.commit();
		return it;
	}
	
	private Integer dumpPerGuid(JsonNode jsonConcepts){
		Integer i = 0;
		
		StorageUnitDumpCallable dsu = new StorageUnitDumpCallable(jsonConcepts);		
		ExecutorService threadPool = Executors.newSingleThreadExecutor();
		Future<Integer> f = threadPool.submit(dsu);
		
		try {
				i = f.get();
		} catch (InterruptedException e) {
			
			e.printStackTrace();
		} catch (ExecutionException e) {
			
			e.printStackTrace();
		}
		
		
		threadPool.shutdown();
		
		
		//System.out.println("DDDDDD Dump pool down? " + threadPool.isShutdown() + " terminated? " + threadPool.isTerminated());
		return i;
		
	}
	
	
	private JsonNode searchPerGuid() throws Exception{
		String res = null;
		JsonNode jsonConcepts;
	
		
		res = getSearch();
	
		if (res != null) {
			ObjectMapper mapper = ClientUtilities.getMapper();
			jsonConcepts = mapper.readTree(res);	
		} else {
			jsonConcepts = null;
		}
		return jsonConcepts;
		
	}
	
	private String getSearch() throws InterruptedException{
		String res = null;
		
		Client client = ClientUtilities.getClient();

		WebResource searchCall = client.resource(searchByGuidUrl + searchGuid);
		
		try{
			res = searchCall.accept(MediaType.APPLICATION_JSON_TYPE).cookie(ClientUtilities.cookie).get(String.class);
		}catch(Exception e){
			if (e instanceof UniformInterfaceException){
				//Thread.sleep(1000);
				res = getSearch();
			}else{
				e.printStackTrace();
			}
			
		}
		
		return res;
		
	}
	
}
